<!--
 * @Description: 基础信息
 * @Author: qingyang
 * @Date: 2022-03-22 18:26:57
 * @LastEditors: qingyang
 * @LastEditTime: 2023-03-07 16:48:48
-->

<template>
  <CFormDetailGroup
    ref="formDetailGroupRef"
    :hiddenOp="true"
    :isEdit="isEdit"
    v-model="componentForm"
    :formConfig="formConfig"
    :loading="submitLoading"
  >
    <CFormDetail ref="baseInfoRef" icon="c-xian-11" title="基础信息填报" :schemas="schemasProduct">
      <template #organizationCodeSlot>
        <el-input
          style="width: 280px"
          v-model:value="componentForm.organizationName"
          disabled
          v-if="isReadOnly || isEdit"
        ></el-input>
        <GSelectOrganization
          style="width: 280px"
          v-model:value="componentForm.organizationCode"
          @change="handleChangeSelectOrganization"
          :isCurrent="true"
          v-else
        ></GSelectOrganization>
      </template>
      <template #applicableYearSlot>
        <el-date-picker
          style="width: 220px"
          :disabled="(isReadOnly || isEdit) && !isCopyEdit"
          v-model="componentForm.applicableYear"
          value-format="YYYY"
          type="year"
          placeholder="请选择"
        >
        </el-date-picker>
      </template>
      <template #fillFrequencySlot>
        <el-radio-group
          v-model="componentForm.fillFrequency"
          :disabled="(isReadOnly || isEdit) && !isCopyEdit"
        >
          <el-radio v-for="item in fillFrequencyOptions" :key="item.value" :label="item.value">{{
            item.label
          }}</el-radio>
        </el-radio-group>
      </template>
      <template #auditorSlot>
        <CSelect
          style="width: 460px"
          v-model="componentForm.auditorId"
          class="table-select"
          placeholder="请选择"
          filterable
          @change="changeAudit"
          :filter-method="handleFilter"
          :disabled="isReadOnly"
        >
          <el-option
            v-for="item in auditorOptions"
            :key="item.userId"
            :value="item.userId"
            :label="item.realName"
          >
            <COption :name="item.realName" :subName="item.email" />
          </el-option>
        </CSelect>
        <el-button
          class="g-ml8"
          type="warning"
          @click="handleUpdateAuditor"
          :loading="updateLoading"
          v-if="isReadOnly && formData.auditorExist === false"
          >更新审核人</el-button
        >
      </template>
    </CFormDetail>
    <CFormDetail
      ref="emissionRef"
      icon="c-xian-21"
      title="附件"
      :schemas="schemasOther"
      foldDisabled
    >
    </CFormDetail>
  </CFormDetailGroup>
</template>
<script lang="ts" setup>
import {
  defineProps,
  defineEmits,
  defineExpose,
  PropType,
  reactive,
  computed,
  watch,
  ref
} from 'vue';
import { CFormDetail, CFormDetailGroup } from '@/components/CFormDetail/index';
import { useDetail } from './useDetail';
import type { GSelectOrganizationOptionItem } from '@/businessComponents/GSelectOrganization/index.vue';
import GSelectOrganization from '@/businessComponents/GSelectOrganization/index.vue';
import {
  saveBaseInfo,
  postEditBaseInfo,
  postInventoryUpdateAuditor
} from '@/apis/eci/inventory/inventory';
import type { IBaseInfo } from '@/apis/eci/inventory/model/inventoryModel';
import { IAuditListItem } from '@/apis/common/model/commonModel';
import { getAuditorList } from '@/apis/common/common';
import { CSelect } from '@/components/CSelect/index';
import { COption } from '@/components/COption/index';
import { useMessage } from '@/hooks/useMessage';
import { fillFrequencyOptions } from '@/constants/enum';

const props = defineProps({
  formData: {
    type: Object as PropType<IBaseInfo>,
    default: () => {
      return {};
    }
  },
  inventoryNo: {
    type: String,
    default: ''
  },
  isReadOnly: {
    type: Boolean,
    default: false
  },
  isCopyEdit: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(['updateAuditId']);

const { schemasProduct, schemasOther, formConfig } = useDetail(props.isCopyEdit);

const baseInfoRef = ref();
const emissionRef = ref();
watch(
  () => props.isReadOnly,
  readonly => {
    if (readonly) {
      baseInfoRef.value?.updateSchema({
        label: '组织边界',
        field: 'boundary',
        type: 'textarea',
        span: 12,
        required: true,
        disabled: true,
        tip: `组织实施经营或财务控制或拥有股份的活动或设施的分组
      推荐写法：
      xxx地址上的工厂内的所有设施与活动。`
      });
      emissionRef.value?.updateSchema({
        label: '厂区平面图',
        field: 'planarFileList',
        type: 'upload',
        disabled: true
      });
    }
  }
);

const isEdit = computed(() => {
  return !!props.inventoryNo;
});

const { createMessage, createConfirm } = useMessage();
const componentForm = reactive(props.formData);
const auditorOptions = ref<Omit<IAuditListItem, 'organizationName'>[]>([]);
const originAuditorOptions = ref<typeof auditorOptions.value>([]); //y原始数据

const loadAuditOptions = () => {
  getAuditorList(componentForm.organizationCode, 'ECI_FILL_TASK_DATA_AUDIT').then(res => {
    const arr = res.map(item => {
      return {
        userId: item.userId.toString(),
        realName: item.realName,
        email: item.email
      };
    });
    originAuditorOptions.value = arr;
    auditorOptions.value = arr;
  });
};
const changeAudit = (val: string) => {
  const index = auditorOptions.value.findIndex(n => val == n.userId);
  if (index > -1) {
    componentForm.auditorEmail = auditorOptions.value[index].email;
    componentForm.auditor = auditorOptions.value[index].realName;
  }
};
watch(
  () => componentForm.organizationCode,
  () => {
    loadAuditOptions();
  }
);
const handleFilter = (val: string) => {
  // 过滤方法
  if (val) {
    auditorOptions.value = originAuditorOptions.value.filter(item => {
      return (
        item.realName.toLowerCase().includes(val.toLowerCase()) ||
        item.email?.toLowerCase().includes(val.toLowerCase())
      );
    });
  }
};

// 选择组织后 自动带出公司
function handleChangeSelectOrganization(value: string, option: GSelectOrganizationOptionItem) {
  console.log('handleChangeSelectOrganization', value, option);
  componentForm.companyName = option?.item.companyName || '';
  componentForm.organizationName = option?.label || '';
  componentForm.companyAddress = option?.item?.companyAddress || '';
  componentForm.contact = option?.item?.contact || '';
  componentForm.contactEmail = option?.item?.contactEmail || '';
  componentForm.contactPhone = option?.item?.contactPhone || '';
}

const updateLoading = ref(false);
async function handleUpdateAuditor() {
  createConfirm('更新审核人', '更新后会将审核人设置成系统固定人员，是否确定？', {
    iconType: 'warning'
  }).then(async () => {
    try {
      updateLoading.value = true;
      const res = await postInventoryUpdateAuditor(componentForm.inventoryNo);
      createMessage.success('更新成功!');
      updateLoading.value = false;
      emits('updateAuditId', res.auditorId);
      if (auditorOptions.value.findIndex(n => res.auditorId == n.userId) === -1) {
        const item = {
          email: res.auditorEmail,
          realName: res.auditor,
          userId: res.auditorId
        };
        auditorOptions.value.push(item);
      }
      console.log('res', res);
    } catch (error) {
      updateLoading.value = false;
      console.log('handleUpdateAuditor error', error);
    }
  });
}

const submitLoading = ref(false);
const formDetailGroupRef = ref();
function check() {
  return new Promise((resolve, reject) => {
    formDetailGroupRef.value?.handleSubmit().then(async (valid: any) => {
      if (valid) {
        const planarGraphName = componentForm.planarFileList[0].name;
        const planarGraphUrl =
          componentForm.planarFileList[0].response?.data?.fileUrl ||
          componentForm.planarFileList[0].url;
        const params = {
          organizationCode: componentForm.organizationCode,
          boundary: componentForm.boundary,
          applicableYear: componentForm.applicableYear,
          planarGraphName: planarGraphName,
          planarGraphUrl: planarGraphUrl,
          fillFrequency: componentForm.fillFrequency,
          auditorId: componentForm.auditorId,
          auditor: componentForm.auditor,
          auditorEmail: componentForm.auditorEmail
        };
        console.log('params', params, isEdit.value);
        // resolve(componentForm.inventoryNo);
        try {
          if (isEdit.value) {
            Object.assign(params, {
              inventoryNo: componentForm.inventoryNo
            });
            await postEditBaseInfo(params);
          } else {
            const no = await saveBaseInfo(params);
            componentForm.inventoryNo = no;
          }
          resolve(componentForm.inventoryNo);
        } catch (error) {
          console.log('check error', error);
          reject(componentForm.inventoryNo);
        }
      }
    });
  });
}

defineExpose({
  check
});
</script>
